package cn.cjlmonster.demo02.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import cn.cjlmonster.demo02.R;

/**
 * This project is Demo02
 * Created by cjl on 2021/11/20 5:47 下午.
 */

public class LanguageAdapter extends RecyclerView.Adapter<LanguageAdapter.Holder> {

    private final LayoutInflater inflater;
    private final String[] languages;
    private int currentIndex = 0;

    public void changeIndex(int index) {
        this.currentIndex = index;
        notifyItemRangeChanged(0, languages.length);
    }

    public LanguageAdapter(Context context, String[] languages, int currentIndex) {
        this.inflater = LayoutInflater.from(context);
        this.languages = languages;
        this.currentIndex = currentIndex;
    }

    @NonNull
    @Override
    public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.item_language, parent, false);
        return new Holder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull Holder holder, int position) {
        holder.tv_language.setText(languages[position]);
        holder.iv_checked.setVisibility(currentIndex == position ? View.VISIBLE : View.INVISIBLE);

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemSelected(this, position, languages[position]);
            }
        });
    }

    @Override
    public int getItemCount() {
        return languages.length;
    }

    static class Holder extends RecyclerView.ViewHolder {
        TextView tv_language;
        ImageView iv_checked;

        public Holder(@NonNull View itemView) {
            super(itemView);
            tv_language = itemView.findViewById(R.id.tv_language);
            iv_checked = itemView.findViewById(R.id.iv_checked);
        }
    }

    private OnItemSelectedListener listener;

    public void setOnItemSelectedListener(OnItemSelectedListener listener) {
        this.listener = listener;
    }

    public interface OnItemSelectedListener {
        void onItemSelected(LanguageAdapter adapter, int position, String language);
    }
}
